<?php  
/**
* 
*/
class ReferenceController extends CI_Controller
{
	
	function __construct()
	{
		parent::__construct();
		$this->load->model('Reference_Model');
	}

	public function index(){
		$session_data = $this->session->userdata('logged_in');

		$data['resultReference'] = $this->Reference_Model->getAllReference();
		$data['allGroup'] = $this->Reference_Model->getAllGroup();

		$this->load->view("include/header");
		$this->load->view("Reference/index",$data);
		$this->load->view("include/footer");

	}

	public function create(){

		$this->load->library('form_validation');
		$this->form_validation->set_rules('name', 'ชื่อ Reference', 'trim|required');
		$this->form_validation->set_message('required','กรุณาใส่ %s ');

		if ($this->form_validation->run() == FALSE)
		{

			$this->index();
		}
		else
		{
			$newid = "R" . sprintf( '%02s' , ((int)substr( $this->Reference_Model->getLastReferenceID() , 1) + 1) );
			$lastCode = $this->Reference_Model->getLastCodeFromGroup($this->input->post('group'));
			$newCode =  substr($lastCode, 0,1) . sprintf( '%02s' ,(int)substr($lastCode, 1) + 1);

			$newRef = array(
				'ref_id' => $newid,
				'ref_group' => $this->input->post('group'),
				'ref_code' => $newCode,
				'ref_name' => $this->input->post('name'),
				'ref_status' => $this->input->post('status')
				);

			$this->Reference_Model->insert($newRef);
			$this->index();
		}

	}

	public function edit($id){

		$data['dataLoad']= $this->Reference_Model->getReferenceWithID($id);

		$this->load->view("include/header");
		$this->load->view("Reference/edit",$data);
		$this->load->view("include/footer");
	}

	public function update($id){

		$this->load->library('form_validation');
			$this->form_validation->set_rules('name', 'ชื่อ Reference', 'trim|required');
			$this->form_validation->set_message('required','กรุณาใส่ %s ');

			if ($this->form_validation->run() == FALSE)
			{
				$this->edit($id);
			}
			else
			{

				$newData = array(
					'ref_name' => iconv('UTF-8', 'TIS-620', $this->input->post('name')),
					'ref_status' => $this->input->post('status')
					);

				$this->Reference_Model->update($id,$newData);
				$this->index();
			}
	}

}
?>